# -*- coding: utf-8 -*-
import os
import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from common.logger import Loggers
 
class ScriptManager:
    def __init__(self):
        self.scheduler = BackgroundScheduler()
        self.scripts = {}
        self.log_dir = "script_logs"
        self.scripts_dir = "scripts"
        self.web_port = 5000
        
        os.makedirs(self.scripts_dir, exist_ok=True)

        # logging.basicConfig(
        #     level=logging.INFO,
        #     format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        # )


        self.logger = Loggers('manage')
    
    # 实际的运行脚本
    def run_script(self, script_path):
        print(f"Running script: {script_path}")
    
        # 在这里执行你的脚本逻辑
        # 例如，使用 subprocess 运行脚本
        import subprocess
        try:
            result = subprocess.run(['python', script_path], capture_output=True, text=True,encoding='utf-8')
            print(result.stdout)  # 打印脚本输出
        except subprocess.SubprocessError as e:
            # print(f"Error running script: {e}")
            self.logger.error(f"运行脚本{script_path} 出错: {e}")


    def add_script(self, script_path, interval_minutes,title):
        if script_path in self.scripts:
            self.logger.warning(f"脚本 {script_path} 已经存在")
            return False
            
        # 确保 interval_minutes 是有效的
        if not isinstance(interval_minutes, (int, float)) or interval_minutes <= 0:
            self.logger.error(f"脚本的无效间隔 {script_path}: {interval_minutes}")
            return False
        
        script_name = os.path.basename(script_path)
        # self.scheduler.add_job(
        #     self.run_script,
        #     'interval',
        #     minutes=interval_minutes,
        #     id=script_path
        # )

        self.scheduler.add_job(
            func=self.run_script,
            args=(script_path,),
            trigger='interval',
            minutes=interval_minutes,
            id=script_path
        )

        
        self.scripts[script_path] = {
            'name': script_name,
            'interval': interval_minutes,
            'status': 'running', # 默认脚本是启动状态
            "title":title,
        }
        
        return True
    
    def remove_script(self, script_path):
        if script_path in self.scripts:
            self.scheduler.remove_job(script_path)
            del self.scripts[script_path]
            return True
        return False
    
    def start_script(self, script_path):
        normalized_path = os.path.normpath(script_path)

        if normalized_path in self.scripts:
            if not self.scheduler.get_job(normalized_path):
                item = self.scripts[normalized_path]
                self.scheduler.add_job(
                    func=self.run_script,
                    args=(normalized_path,),
                    trigger='interval',
                    minutes=self.scripts[normalized_path]['interval'],
                    id=normalized_path
                )
            self.scripts[normalized_path]['status'] = 'running'
            return True
        return False
    
    def stop_script(self, script_path):
        self.logger.info('停止脚本'+script_path)
        normalized_path = os.path.normpath(script_path)
        if normalized_path in self.scripts:
            if self.scheduler.get_job(normalized_path):
                self.scheduler.pause_job(normalized_path)
            self.scripts[normalized_path]['status'] = 'stopped'
            return True
        return False
    
    def clear_script(self,script_path):
        if script_path in self.scripts:
            now = datetime.datetime.now()
            with open(script_path, 'w', encoding='utf-8') as f:
                f.write(f"{now}  日志已清理\n\n")
            return True
        return False
    def resume_script(self, script_path):
        if script_path in self.scripts:
            if self.scheduler.get_job(script_path):
                self.scheduler.resume_job(script_path)
            self.scripts[script_path]['status'] = 'running'
            return True
        return False
    
    def start(self):
            # 清理所有现有的任务
        # self.scheduler.remove_all_jobs()

        self.scheduler.start()
        self.logger.info("任务调度启动")
        
        self.start_web_server()
    
    def start_web_server(self):
        from .web import start_web_app
        start_web_app(self)
    
    def stop(self):
        self.scheduler.shutdown()
        self.logger.info("脚本管理器停止")
 
